package com.stox.shared.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Renko extends Bar {

	private final boolean up;
	private final double reversalSize;
	private final List<Bar> bars = new ArrayList<>();

	public Renko(final boolean up, final double reversalSize, final double low, final Date initialDate) {
		this.up = up;
		this.reversalSize = reversalSize;
		super.setHigh(low + reversalSize);
		super.setLow(low);
		setClose(low); // low is being treated as initial close
		setDate(initialDate);
	}

	public Renko consume(final Bar bar) {
		final double value = getValue(bar);
		if ((value <= (getHigh() + reversalSize)) && (value >= (getLow() - reversalSize))) {
			doConsume(bar);
			return this;
		} else {
			final boolean nextUp = value > getHigh();
			return new Renko(nextUp, reversalSize, nextUp ? getHigh() : getLow() - reversalSize, getDate());
		}
	}

	@Override
	public void setHigh(final double high) {
		throw new UnsupportedOperationException();
	}

	@Override
	public void setLow(final double low) {
		throw new UnsupportedOperationException();
	}

	private void doConsume(final Bar bar) {
		final double value = getValue(bar);
		if (0 == getOpen()) {
			setOpen(value);
		}
		setClose(value);
		setVolume(getVolume() + bar.getVolume());
		setDate(bar.getDate());
		setScrip(bar.getScrip());
		setScripId(bar.getScripId());
		bars.add(bar);
	}

	private double getValue(final Bar bar) {
		return bar.getClose();
	}

	public boolean isUp() {
		return up;
	}

}
